<template>
  <div class="HomePageView">
    <div class="page-view">
      <div class="describe">
        <span>{{$t('message.homePageTable.title')}}</span>
        <p class="r-describe">
          <button class="black-btn" @click="centerDialogVisible = true">
            <i class="el-icon-plus"></i>
            <span>{{$t('message.public.uploaded')}}</span>
          </button>
          <!-- <i class="el-icon-upload2" ></i> -->
          <i class="el-icon-refresh" @click="getData"></i>
          <i class="el-icon-delete-solid" @click="tableDataDelete()"></i>
        </p>
      </div>
      <div class="tableView">
        <div ref="tableCot">
          <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            :max-height="tableHeight"
            :header-cell-style="{color:'rgba(144,147,153,1)',fontSize:'16px',textAlign:'left'}"
            :cell-style="{color: 'rgba(96,98,102,1)',backgroundColor:'transparent',fontSize:'14px',textAlign:'left'}"
            :row-style="{color: 'rgba(96,98,102,1)',backgroundColor:'transparent',fontSize:'13px',textAlign:'left'}"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column :label="$t('message.homePageTable.name')" width="300">
              <template slot-scope="scope">
                <span
                  @click="pushCAD(scope.row)"
                  style="cursor: pointer;"
                >{{scope.row.name + `.${scope.row.ext}` }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="size" :label="$t('message.homePageTable.size')" width="150">
              <template slot-scope="scope">{{scope.row.size + ' kb'}}</template>
            </el-table-column>
            <el-table-column
              prop="modifyTime"
              :label="$t('message.homePageTable.updated')"
              sortable
            ></el-table-column>
            <el-table-column prop="status" :label="$t('message.homePageTable.status')">
              <template slot-scope="scope">
                <span v-if="scope.row.status == 1">{{$t('message.homePageTable.unfinished')}}</span>
                <span v-if="scope.row.status == 2">{{$t('message.homePageTable.uploaded')}}</span>
                <span v-if="scope.row.status == 3">{{$t('message.homePageTable.changingFiles')}}</span>
                <span v-if="scope.row.status == 4">{{$t('message.homePageTable.finished')}}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('message.homePageTable.action')">
              <template slot-scope="scope">
                <el-dropdown placement="bottom-start" trigger="hover">
                  <span class="el-dropdown-link">
                    <i class="el-icon-s-unfold"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <div class="dropdown-view" @click="pushCAD(scope.row)">
                      <i class="iconfont">&#xe6c4;</i>
                      <!-- <router-link
                        target="_blank"
                        :to="{path:'/CAD',query:{fileID:`${scope.row.id}`}}"
                      >
                      
                      </router-link>-->
                      <span>{{$t('message.homePageTable.browse')}}</span>
                    </div>
                    <div class="dropdown-view" @click="editFileName(scope.row)">
                      <i class="iconfont">&#xe6c5;</i>
                      <span>{{$t('message.homePageTable.rename')}}</span>
                    </div>
                    <div class="dropdown-view" @click="downData(scope.row)">
                      <i class="iconfont">&#xe6c6;</i>
                      <span>{{$t('message.homePageTable.download')}}</span>
                    </div>
                    <!-- <div class="dropdown-view">
                      <i class="iconfont">&#xe6c7;</i>
                      <span>复制或移动</span>
                    </div>-->
                    <div class="dropdown-view" @click="delectData(scope.row)">
                      <i class="iconfont">&#xe6c8;</i>
                      <span>{{$t('message.homePageTable.delete')}}</span>
                    </div>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="Pagination-box">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="tableForm.pageIndex"
          :page-size="tableForm.pageSize"
          :page-sizes="[10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        ></el-pagination>
      </div>
      <!-- <div class="footer">
        <span>{{$t('message.homePageTable.capacity')}}：0.32MB/1.0G</span>
      </div>-->
      <el-dialog
        :title="$t('message.public.uploaded')"
        :visible.sync="centerDialogVisible"
        width="30%"
        center
        :append-to-body="true"
      >
        <el-upload
          class="upload-demo"
          drag
          :action="action"
          multiple
          ref="upload"
          style="textAlign:center;"
          :on-error="uploadFalse"
          :on-success="uploadSuccess"
          :auto-upload="false"
          :before-upload="beforeAvatarUpload"
          :data="form"
          :file-list="fileList"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{$t('message.homePageTable.downloadmsg')}}
            <em>{{$t('message.homePageTable.finishedFile')}}</em>
          </div>
          <div class="el-upload__tip" slot="tip">{{$t('message.homePageTable.uploadedTip')}}</div>
        </el-upload>
        <span slot="footer" class="dialog-footer">
          <el-button @click="onCancel" size="small">{{$t('message.public.cancel')}}</el-button>
          <el-button
            type="primary"
            size="small"
            @click="submitUpload()"
          >{{$t('message.public.confirm')}}</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :title="$t('message.homePageTable.rename')"
        :visible.sync="fileNameFlag"
        width="30%"
        center
        :append-to-body="true"
      >
        <el-form label-position="right" label-width="80px" :model="formLabelAlign">
          <el-form-item label="File Name">
            <el-input v-model="formLabelAlign.fileName" size="small"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="fileNameFlag = false">{{$t('message.public.cancel')}}</el-button>
          <el-button
            type="primary"
            size="small"
            @click="submitFileName()"
          >{{$t('message.public.confirm')}}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { GetFile, DelFile, updateFile } from "../../api/api";
import BASE from "../../utils/base";
import { getLocalStorage } from "../../utils/storage";
import $ from "jquery";
// 导出模块
export default {
  // 模块名字
  name: "HomePageView",
  // 模块数据
  data() {
    //数据
    return {
      tableData: [],
      total: 0,
      tableForm: {
        pageIndex: 1,
        pageSize: 10,
        fileID: "",
        userID: getLocalStorage("userID"),
      },
      fileList: [],
      action: BASE.TEST_IP + "/api/File/addFile",
      centerDialogVisible: false,
      form: {
        creator: getLocalStorage("userID"),
        modifier: getLocalStorage("userID"),
        UserID: getLocalStorage("userID")
      },
      multipleSelection: [],
      formLabelAlign: {
        id: "",
        fileName: "",
      },
      fileNameFlag: false,
      tableHeight: 590,
      connection: "", //signalr连接
      messages: [], //返回消息
    };
  },
  // 注册组件
  components: {},
  // 监听指定值，只有指定值变化，才会触发
  watch: {},
  // 里面的函数只有调用才会执行（实时计算）里面是定义的方法
  methods: {
    handleSizeChange(val) {
      this.tableForm.pageSize = val;
      GetFile(this.tableForm).then((res) => {
        this.tableData = [];
        this.total = 0;
        if (res.data.code != 0) {
          return;
        }
        this.tableData = res.data.data;
        this.total = res.data.count;
      });
    },
    handleCurrentChange(val) {
      this.tableForm.pageIndex = val;
      GetFile(this.tableForm).then((res) => {
        this.tableData = [];
        this.total = 0;
        if (res.data.code != 0) {
          return;
        }
        this.tableData = res.data.data;
        this.total = res.data.count;
      });
    },
    getData() {
      console.log(this.tableForm)
      GetFile(this.tableForm).then((res) => {
        console.log(res);
        this.tableData = [];
        this.total = 0;
        if (res.data.code != 0) {
          return;
        }
        this.tableData = res.data.data;
        this.total = res.data.count;
      });
    },
    //文件上传成功触发
    uploadSuccess(response, file, fileList) {
      if (response.code == 0) {
        this.getData();
        this.fileList = [];
        this.$message({
          message: this.$t("message.homePageTable.suploaded"),
          type: "success",
        });
        this.centerDialogVisible = false;
      } else {
        this.$message({
          message: this.$t("message.homePageTable.euploaded"),
          type: "error",
        });
      }
    },
    //文件上传失败触发
    uploadFalse(response, file, fileList) {
      this.$message({
        message: "文件上传失败！",
        type: "error",
      });
    },
    // 上传前对文件的大小和类型的判断
    beforeAvatarUpload(file) {
      this.form.fileName = file.name;
      const extension = file.name.split(".")[1] === "dxf";
      const extension2 = file.name.split(".")[1] === "dwg";
      const extension3 = file.name.split(".")[1] === "wmf";
      const extension4 = file.name.split(".")[1] === "png";
      const extension5 = file.name.split(".")[1] === "jpg";
      const extension6 = file.name.split(".")[1] === "gif";
      const extension7 = file.name.split(".")[1] === "tif";
      const extension8 = file.name.split(".")[1] === "tiff";
      const extension9 = file.name.split(".")[1] === "bmp";
      if (
        !extension &&
        !extension2 &&
        !extension3 &&
        !extension4 &&
        !extension5 &&
        !extension6 &&
        !extension7 &&
        !extension8 &&
        !extension9
      ) {
        this.$message({
          message: this.$t("message.homePageTable.uploadedTip"),
          type: "error",
        });
      }
      return (
        extension ||
        extension2 ||
        extension3 ||
        extension4 ||
        extension5 ||
        extension6 ||
        extension7 ||
        extension8 ||
        extension9
      );
    },
    //表单提交
    submitUpload() {
      this.$refs.upload.submit();
    },
    //表单取消
    onCancel() {
      this.fileList = [];
      this.centerDialogVisible = false;
    },
    //文件删除
    delectData(row) {
      this.$confirm(
        this.$t("message.public.filetips"),
        this.$t("message.public.delete"),
        {
          confirmButtonText: this.$t("message.public.confirm"),
          cancelButtonText: this.$t("message.public.cancel"),
          type: "warning",
        }
      )
        .then(() => {
          let data = {
            id: [row.id],
            userID: this.tableForm.userID,
          };
          DelFile(data).then((res) => {
            let totalPage = Math.ceil(
              (this.total - 1) / this.tableForm.pageSize
            );
            let currentPage =
              this.tableForm.pageIndex > totalPage
                ? totalPage
                : this.tableForm.pageIndex;
            this.tableForm.pageIndex =
              this.tableForm.pageIndex < 1 ? 1 : currentPage;
            this.getData();
          });
        })
        .catch(() => {});
    },
    downData(row) {
      let name = row.name + "." + row.ext;
      let url = row.sourcePath;
      this.fdownload(url, name);
    },
    fdownload(url, filename) {
      let _this = this;
      this.getBlob(url, function (blob) {
        _this.saveAs(blob, filename);
      });
    },
    getBlob(url, cb) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = function () {
        if (xhr.status === 200) {
          cb(xhr.response);
        }
      };
      xhr.send();
    },
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        var link = document.createElement("a");
        var body = document.querySelector("body");
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    tableDataDelete() {
      if (this.multipleSelection.length == 0) {
        return;
      }
      let id_list = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        id_list.push(this.multipleSelection[i].id);
      }
      this.$confirm(
        this.$t("message.public.filetips"),
        this.$t("message.public.delete"),
        {
          confirmButtonText: this.$t("message.public.confirm"),
          cancelButtonText: this.$t("message.public.cancel"),
          type: "warning",
        }
      )
        .then(() => {
          let data = {
            id: id_list,
            userID: this.tableForm.userID,
          };
          DelFile(data).then((res) => {
            let totalPage = Math.ceil(
              (this.total - 1) / this.tableForm.pageSize
            );
            let currentPage =
              this.tableForm.pageIndex > totalPage
                ? totalPage
                : this.tableForm.pageIndex;
            this.tableForm.pageIndex =
              this.tableForm.pageIndex < 1 ? 1 : currentPage;
            this.getData();
          });
        })
        .catch(() => {});
    },
    editFileName(row) {
      this.fileNameFlag = true;
      this.formLabelAlign.id = row.id;
    },
    submitFileName() {
      updateFile(this.formLabelAlign).then((res) => {
        this.fileNameFlag = false;
        if (res.data.code != 0) {
          this.$message.error(res.data.msg);
          return;
        }
        this.getData();
      });
    },
    pushCAD(row) {
      if (
        row.ext == "dxf" ||
        row.ext == "dwg" ||
        row.ext == "svg" ||
        row.ext == "wmf"
      ) {
        var { href } = this.$router.resolve({
          name: "CAD",
          query: {
            id: row.id,
          },
        });
      } else {
        var { href } = this.$router.resolve({
          name: "PicView",
          query: {
            id: row.id,
          },
        });
      }

      window.open(href, "_blank");
    },
    // sendAll: function () {
    //   this.$socket
    //     .invoke("SendMessage", this.user, this.message)
    //     .catch(function (err) {
    //       return console.error(err);
    //     });
    // },
  },
  // 创建前状态(里面是操作)
  beforeCreate() {},
  // 创建完毕状态(里面是操作)
  created() {
    this.getData();
    let that = this;
    this.$nextTick(function () {
      let heightStyle = $(".page-view").height() - 240;
      that.tableHeight = heightStyle;
    });
    // 后台推送
    this.$socket.on("ReceiveMessage", function (id, status) {
      if (id && status) {
        for (let i = 0; i < that.tableData.length; i++) {
          if (that.tableData[i].id == id) {
            that.tableData[i].status = status;
          }
        }
      }
    });
    this.$socket.start();
  },
  // 挂载前状态(里面是操作)
  beforeMount() {},
  // 挂载结束状态(里面是操作)
  mounted() {
    const that = this;
    this.$nextTick(function () {
      window.onresize = () => {
        return (() => {
          let heightStyle = $(".page-view").height() - 240;
          that.tableHeight = heightStyle;
        })();
      };
    });
  },
  // 更新前状态(里面是操作)
  beforeUpdate() {},
  // 更新完成状态(里面是操作)
  updated() {},
  // 销毁前状态(里面是操作)
  beforeDestroy() {},
  // 销毁完成状态(里面是操作)
  destroyed() {},
};
</script>
<style  lang="scss" scoped>
.HomePageView {
  width: calc(100% - 257px);
  height: 100%;
  .page-view {
    position: relative;
    width: calc(100% - 112px);
    height: calc(100% - 48px);
    margin: 22px 24px 26px 24px;
    background: rgba(255, 255, 255, 1);
    border-radius: 2px;
    border: 1px solid #b4b4b4;
    padding: 0 32px;
    .describe {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 16px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
      padding: 34px 0 34px 0px;
      font-weight: bold;
    }
    .black-btn {
      padding: 0 8px;
      height: 32px;
      font-size: 14px;
      color: rgba(255, 255, 255, 1);
      background: #213d49;
      border-radius: 4px;
      font-weight: 500;
      margin: 0 24px;
      span {
        margin: 0 0 0 8px;
      }
    }
    .r-describe {
      display: flex;
      align-items: center;
      .el-icon-upload2,
      .el-icon-download,
      .el-icon-delete-solid,
      .el-icon-refresh {
        font-size: 24px;
        color: rgba(144, 147, 153, 1);
        margin: 0 8px;
        cursor: pointer;
      }
    }
    .footer {
      position: absolute;
      width: 100%;
      bottom: 0;
      left: 0;
      height: 47px;
      line-height: 47px;
      border-top: 1px solid rgba(229, 229, 229, 1);
      span {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.45);
        margin-left: 34px;
      }
    }
  }
  ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: #fff1f0 !important;
  }
  .el-icon-s-unfold {
    font-size: 24px;
    position: relative;
    cursor: pointer;
  }
}
.Pagination-box {
  position: absolute;
  right: 32px;
  bottom: 80px;
  ::v-deep .el-pagination.is-background .btn-next,
  ::v-deep .el-pagination.is-background .btn-prev,
  ::v-deep .el-pagination.is-background .el-pager li {
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    color: rgba(0, 0, 0, 0.65);
    font-size: 14px;
    border: 1px solid rgba(217, 217, 217, 1);
  }
  // ::v-deep .el-pagination.is-background .el-pager li {
  //   background:rgba(30,30,30,1);
  //   color:rgba(255,255,255,1);
  // }
  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background: #213d49;
    color: rgba(255, 255, 255, 1);
  }
  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled):hover {
    color: none;
  }
}

.dropdown-view {
  width: 160px;
  height: 40px;
  line-height: 40px;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  cursor: pointer;
  .iconfont {
    font-size: 24px;
    margin: 0 8px;
  }
}
.dropdown-view:hover {
  background: #fff1f0;
}

::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #213d49;
  border-color: #213d49;
  color: #001529;
}
::v-deep .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #213d49;
  border-color: #213d49;
  color: #001529;
}
::v-deep .el-checkbox__inner:hover {
  background-color: #213d49;
}
::v-deep .el-checkbox__inner:hover {
  background-color: #213d49;
  color: #001529;
}
::v-deep .el-checkbox__inner:hover {
  border-color: #213d49;
}
</style>
 